//
//  FKShareImageTextVC.m
//  HappyTest
//
//  Created by Macbook Pro on 2019/2/15.
//  Copyright © 2019 Macbook Pro. All rights reserved.
//

#import "FKShareImageTextVC.h"
#import "FKFastShareCell.h"
#import "FKFastShareModel.h"
#import "FKCommodityDetailVC.h"
#import <GKPhotoBrowser.h>
#import <Photos/PHAsset.h>
#import <Photos/PHAssetChangeRequest.h>
#import "FKShareChooseImageView.h"
#import "FKShareNowView.h"
#import <UShareUI/UShareUI.h>
#import "FKSharePhotoBrower.h"
#import "FKFastShareTool.h"

@interface FKShareImageTextVC ()<FKFastShareCellDelegate>

/** 保存分享素材的id，添加次数需要 */
@property (nonatomic, copy) NSString *itemId;

@end

@implementation FKShareImageTextVC

- (NSArray *)datas
{
    if (!_datas) {
        _datas = [NSArray array];
    }
    return _datas;
}

//- (void)refreshData
//{
//    if (self.datas.count == 0) [self loadData];
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 12, 0, 12);
    self.tableView.tableFooterView = [UIView new];
    self.tableView.autoresizingMask = UIViewAutoresizingNone;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FKFastShareCell *cell = [FKFastShareCell cellWith:tableView];
    cell.delegate = self;
    cell.data = self.datas[indexPath.row];
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FKFastShareModel *model = self.datas[indexPath.row];
    return model.cellH;
}

#pragma mark - FKFastShareCellDelegate
- (void)fastShareCell:(FKFastShareCell *)cell didTapImageView:(NSInteger)index
{
//    FKFastShareModel *model = cell.data;
//    NSMutableArray *photos = [NSMutableArray new];
//    for (NSString *url in model.imgs) {
//        GKPhoto *photo = [GKPhoto new];
//        photo.url = [NSURL URLWithString:url];
//        [photos addObject:photo];
//    }
//    GKPhotoBrowser *browser = [GKPhotoBrowser photoBrowserWithPhotos:photos currentIndex:index];
//    browser.showStyle = GKPhotoBrowserShowStyleNone;
//    [browser showFromVC:self];
    
    FKFastShareModel *model = cell.data;
    FKSharePhotoBrower *brower = [[FKSharePhotoBrower alloc] init];
    brower.saleTime = self.timeDict[@"saleTime"];
    brower.activeTime = self.timeDict[@"activeTime"];
    brower.images = model.imgs;
    brower.url = self.goodsUrl;
    brower.currentIndex = index;
    [brower show];
}

- (void)fastShareCellDidClickedCopyBtn:(FKFastShareCell *)cell
{
    FKFastShareModel *model = cell.data;
    self.itemId = model.id;
    [self addShareCount];
    
    // 将文字添加到剪贴板
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = model.info;
    NSDictionary *userInfo = [FKCacheTool userInfo];
    if (model.imgs.count > 0) {
        [SVProgressHUD show];
        [FKFastShareTool createPhotosWith:model.imgs qrcodeUrl:self.goodsUrl saleTime:self.timeDict[@"saleTime"] activeTime:self.timeDict[@"activeTime"] level:userInfo[@"level"] complete:^(NSArray<UIImage *> * _Nonnull images) {
            [FKFastShareTool saveImages:images completion:^{
                [SVProgressHUD showSuccessWithStatus:@"文案复制成功"];
            }];
        }];
    } else {
        [SVProgressHUD showSuccessWithStatus:@"文案复制成功"];
    }
}

///** 保存图片到相册 */
//- (void)saveImages:(NSArray<UIImage *> *)images completion:(void (^)(void))completion
//{
//    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    dispatch_group_t group = dispatch_group_create();
//    for (UIImage *image in images) {
//        dispatch_group_enter(group);
//        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
//            [PHAssetChangeRequest creationRequestForAssetFromImage:image];
//        } completionHandler:^(BOOL success, NSError * _Nullable error) {
//            dispatch_group_leave(group);
//        }];
//    }
//
//    dispatch_group_notify(group, queue, ^{
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if (completion) completion();
//        });
//        FKLog(@"全部保存完毕");
//    });
//}

- (void)fastShareCellDidClickedWechatTimeline:(FKFastShareCell *)cell
{
    FKFastShareModel *model = cell.data;
    self.itemId = model.id;
    NSDictionary *userInfo = [FKCacheTool userInfo];

    if ([model.market_type isEqualToString:@"1"]) { // 有图片
        // 生成带二维码的图片
//        fkWeakSelf(self);
        [SVProgressHUD show];
        [FKFastShareTool createPhotosWith:model.imgs qrcodeUrl:self.goodsUrl saleTime:self.timeDict[@"saleTime"] activeTime:self.timeDict[@"activeTime"] level:userInfo[@"level"] complete:^(NSArray<UIImage *> * _Nonnull images) {
            [SVProgressHUD dismiss];
            FKShareChooseImageView *view = [[FKShareChooseImageView alloc] init];
            view.type = 1;
            view.images = images;
            [view show];
            view.bottomBtnBlock = ^(NSArray * _Nonnull urls) {
                // 保存图片到相册
                [SVProgressHUD show];
                [FKFastShareTool saveImages:images completion:^{
                    [SVProgressHUD dismiss];
                    FKShareNowView *view = [[FKShareNowView alloc] init];
                    [view show];
                }];
            };
        }];
        
    } else { // 分享链接
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:model.url_title descr:model.info thumImage:[UIImage imageNamed:@"AppIcon"]];
        shareObject.webpageUrl = model.url;
        messageObject.shareObject = shareObject;
        [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatTimeLine messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            if (error) {
                [SVProgressHUD showErrorWithStatus:@"分享失败"];
            } else {
                [SVProgressHUD showSuccessWithStatus:@"分享成功"];
                [self addShareCount];
            }
        }];
    }
}

- (void)fastShareCellDidClickedWechatSession:(FKFastShareCell *)cell
{
    __block FKFastShareModel *model = cell.data;
    self.itemId = model.id;
    NSDictionary *userInfo = [FKCacheTool userInfo];

    if ([model.market_type isEqualToString:@"1"]) {
        fkWeakSelf(self);
        [SVProgressHUD show];
        [FKFastShareTool createPhotosWith:model.imgs qrcodeUrl:self.goodsUrl saleTime:self.timeDict[@"saleTime"] activeTime:self.timeDict[@"activeTime"] level:userInfo[@"level"] complete:^(NSArray<UIImage *> * _Nonnull images) {
            [SVProgressHUD dismiss];
            FKShareChooseImageView *view = [[FKShareChooseImageView alloc] init];
            view.type = 2;
            view.images = images;
            [view show];
            view.bottomBtnBlock = ^(NSArray * _Nonnull urls) {
                __block NSMutableArray *activityItems = [NSMutableArray array];
                [activityItems addObject:model.info];
                for (UIImage *image in images) {
                    [activityItems addObject:image];
                }
                UIActivityViewController *activityVc = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
                
                activityVc.excludedActivityTypes = @[UIActivityTypePostToFacebook     ,
                                                     UIActivityTypePostToTwitter      ,
                                                     UIActivityTypePostToWeibo        ,
                                                     UIActivityTypeMessage            ,
                                                     UIActivityTypeMail               ,
                                                     UIActivityTypePrint              ,
                                                     UIActivityTypeCopyToPasteboard   ,
                                                     UIActivityTypeAssignToContact    ,
                                                     //                  UIActivityTypeSaveToCameraRoll   ,
                                                     UIActivityTypeAddToReadingList   ,
                                                     UIActivityTypePostToFlickr       ,
                                                     UIActivityTypePostToVimeo        ,
                                                     UIActivityTypePostToTencentWeibo ,
                                                     //                  UIActivityTypeAirDrop            ,
                                                     UIActivityTypeOpenInIBooks       ,
//                                                     UIActivityTypeMarkupAsPDF
                                                     ];
                [weakself presentViewController:activityVc animated:YES completion:nil];
                activityVc.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
                    if (completed) {
                        FKLog(@"分享成功");
                        [self addShareCount];
                    } else {
                        FKLog(@"分享失败");
                    }
                };
            };
        }];
        
    } else {
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:model.url_title descr:model.info thumImage:[UIImage imageNamed:@"AppIcon"]];
        shareObject.webpageUrl = model.url;
        messageObject.shareObject = shareObject;
        [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatSession messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            if (error) {
                [SVProgressHUD showErrorWithStatus:@"分享失败"];
            } else {
                [SVProgressHUD showSuccessWithStatus:@"分享成功"];
                [self addShareCount];
            }
        }];
    }
}

/**
 添加分享次数
 itemsId：素材id
 */
- (void)addShareCount
{
    if (!self.itemId) return;
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"goods_share_id"] = self.itemId;
    self.itemId = nil; // 用完记得清空
    [FKHttpTool postWithSuffix:@"m=Home&c=Item&a=share" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            FKLog(@"-----添加分享次数成功-----");
        }
    } failure:nil];
}

@end
